<script setup lang='ts'>
defineOptions({
  name: 'AppGlobalSearch',
})
const props = defineProps<{
  autoFocus?: boolean
}>()
const emit = defineEmits(['gameTypeChange', 'close', 'focus'])
const { isMobile } = storeToRefs(useWindowStore())
const { t } = useI18n()
const route = useRoute()
const showSheet = ref(false)
const dropdownVisible = ref(false)
const { bool: isPopperShow, setTrue, setFalse } = useBoolean(false)
const {
  bool: isShowOverlay,
  setTrue: showOverlayTrue,
  setFalse: showOverlayFalse,
} = useBoolean(false)
const { bool: isClear, setTrue: setClearTrue } = useBoolean(true)
const {
  bool: isInputing, setTrue: setInputingTrue,
  setFalse: setInputingFalse,
} = useBoolean(false)
const initCasino = route.name?.toString().includes('casino')
const initSports = route.name?.toString().includes('sports')
const initOthers = !initCasino && !initSports
const {
  bool: isShowTypeSelect,
  setTrue: showTypeSelect,
  setFalse: hideTypeSelect,
} = useBoolean(!initOthers)

// 搜索栏
const gameType = ref(initCasino ? '1' : initSports ? '2' : '1')
const gameTypeList = [
  { label: t('casino'), value: '1' },
  { label: t('sports'), value: '2' },
]
const searchValue = ref('')
const baseSearchRef = ref()
// 近期搜索关键字
const keywordLive = ref(
  Local.get<any[]>(STORAGE_SEARCH_KEYWORDS_LIVE)?.value ?? [],
)
const keywordSports = ref(
  Local.get<any[]>(STORAGE_SEARCH_KEYWORDS_SPORTS)?.value ?? [],
)

const gameLabel = computed(() => {
  return gameTypeList.find(a => a.value === gameType.value)?.label ?? '-'
})
const goodSearchValue = computed(() => searchValue.value.length >= 3)
const isCasino = computed(() => gameType.value === '1')
const isSports = computed(() => gameType.value === '2')
const keywordList = computed(() => {
  if (isCasino.value)
    return keywordLive.value
  else if (isSports.value)
    return keywordSports.value
  return []
})
const searchPlaceholder = computed(() => isCasino.value
  ? t('search_game')
  : t('search_events'))
// 娱乐城搜索接口
const {
  list: casinoGames,
  run: runSearchCasinoGames,
} = useList(ApiMemberGameSearch, {
  // debounceInterval: 500,
  onSuccess(res, params) {
    if (res.d && res.d.length > 0) {
      const word = params[0].w
      isClear.value = false

      // 去重
      if (keywordLive.value.includes(word))
        keywordLive.value.splice(keywordLive.value.findIndex(t => t === word), 1)

      keywordLive.value.unshift(word)
      keywordLive.value = keywordLive.value.slice(0, 5)
      Local.set(STORAGE_SEARCH_KEYWORDS_LIVE, keywordLive.value)
    }
    setInputingFalse()
  },
})
// 体育搜索接口
const { data: sportsData, run: runSearchSports } = useRequest(
  () => ApiSportEventSearch({ word: searchValue.value }),
  {
    // debounceInterval: 500,
    onSuccess(res) {
      if (res.list && res.list.length > 0) {
        const word = searchValue.value
        isClear.value = false

        // 去重
        if (keywordSports.value.includes(word))
          keywordSports.value.splice(keywordSports.value.findIndex(t => t === word), 1)

        keywordSports.value.unshift(word)
        keywordSports.value = keywordSports.value.slice(0, 5)
        Local.set(STORAGE_SEARCH_KEYWORDS_SPORTS, keywordSports.value)
      }
      setInputingFalse()
    },
  },
)
// 搜索结果
const resultData = computed(() => {
  if (isClear.value || !goodSearchValue.value)
    return null
  if (isCasino.value)
    return casinoGames.value.length > 0 ? casinoGames.value : null
  if (isSports.value && sportsData.value && sportsData.value.list)
    return sportsData.value.list

  return null
})

let inputTimer: any = null
function onBaseSearchInput() {
  setInputingTrue()
  clearTimeout(inputTimer)
  if (searchValue.value.length < 3) {
    setInputingFalse()
    setClearTrue()
    return
  }
  inputTimer = setTimeout(() => {
    if (isCasino.value && searchValue.value.length >= 3) {
      Local.set(STORAGE_CLEAR_LIVE, true)
      runSearchCasinoGames({ w: searchValue.value })
    }
    else if (isSports.value && searchValue.value.length >= 3) {
      Local.set(STORAGE_CLEAR_SPORTS, true)
      runSearchSports()
    }
    clearTimeout(inputTimer)
  }, 500)
}
function onClickKeyword(k: string) {
  setInputingTrue()
  searchValue.value = k
  if (isCasino.value)
    runSearchCasinoGames({ w: searchValue.value })
  else if (isSports.value)
    runSearchSports()
}
function onCloseKeyword(k: string) {
  if (isCasino.value) {
    keywordLive.value.splice(keywordLive.value.findIndex(t => t === k), 1)
    Local.set(STORAGE_SEARCH_KEYWORDS_LIVE, keywordLive.value)
  }
  else if (isSports.value) {
    keywordSports.value.splice(keywordSports.value.findIndex(t => t === k), 1)
    Local.set(STORAGE_SEARCH_KEYWORDS_SPORTS, keywordSports.value)
  }
}
function selectGameType(v: string) {
  gameType.value = v
  emit('gameTypeChange', v)
}
function clearKeyword() {
  if (isCasino.value) {
    Local.set(STORAGE_CLEAR_LIVE, true)
    keywordLive.value.length = 0
    Local.remove(STORAGE_SEARCH_KEYWORDS_LIVE)
  }
  else if (isSports.value) {
    Local.set(STORAGE_CLEAR_SPORTS, true)
    keywordSports.value.length = 0
    Local.remove(STORAGE_SEARCH_KEYWORDS_SPORTS)
  }
}
function handleFocus() {
  showOverlayTrue()
  showTypeSelect()
    emit('focus')
}
// 关闭方法
function emitClose() {
  searchValue.value = ''
  showOverlayFalse()
  initOthers && hideTypeSelect()
  emit('close')
}
function intiKeyword() {
  if (!Local.get(STORAGE_CLEAR_LIVE)?.value) {
    const liveList = [
      'Monopoly',
      'Crazy Time',
      'Sweet Bonanza',
      'Money Train',
      'Reactoonz',
    ]
    Local.set(STORAGE_SEARCH_KEYWORDS_LIVE, liveList)
    keywordLive.value = liveList
  }

  if (!Local.get(STORAGE_CLEAR_SPORTS)?.value) {
    const sportsList = [
      'Liverpool FC',
      'Kansas City Chiefs',
      'Los Angeles Lakers',
      'FC Barcelona',
      'FC Bayern Munich',
    ]
    Local.set(STORAGE_SEARCH_KEYWORDS_SPORTS, sportsList)
    keywordSports.value = sportsList
  }
}

provide('closeSearch', emitClose)

onMounted(() => {
  if (props.autoFocus)
    baseSearchRef.value.manualFocus()
  useFixedTop('.app-global-search')
})

// intiKeyword()
</script>

<template>
  <div class="relative overflow-visible" :class="{ 'in-pc': !isMobile }">
    <div v-show="!isMobile" class="overlay" @click="emitClose" />
    <BaseInput
      ref="baseSearchRef"
      v-model.trim="searchValue"
      class="search-input sticky top-0 z-100"
      :placeholder="searchPlaceholder"
      :clearable="isShowOverlay || searchValue.length > 0"
      @focus="handleFocus"
      @clear="setClearTrue"
      search
      @close="emitClose"
      @input="onBaseSearchInput"
      name="search"
    >
      <template #left-icon>
        <BaseDropdown position="right" @toggle="val => dropdownVisible = val">
          <template v-slot:trigger>
            <div class="flex border-r border-r-border-black-4 px-[0.5rem] w-[4.375rem] items-center">
              <span class="mr-[0.25rem]">{{gameTypeList.find(item => item.value === gameType)?.label}}</span>
              <div :class="[dropdownVisible && 'rotate-180']" class="transition h-[0.75rem]">
                <BaseIcon name="uni-arrow-down" className="!text-text-white-2" size="size-[1.125rem]"/>
              </div>
            </div>
          </template>
          <!-- <template v-slot:menu>
            <div @click="selectGameType(item.value)" class="text-center py-[.375rem] w-[5rem]" v-for="item in gameTypeList" :key="item.value">{{item.label}}</div>
          </template> -->
        </BaseDropdown>
      </template>
    </BaseInput>
    <BaseSheet
        v-model="dropdownVisible"
        title="  "
        :items="gameTypeList"
    >
        <template  #default="{ item, index }: { item?: any, index?: number }">
            <li
            class="mx-[0.875rem] h-[2.5rem] px-[0.5rem] rounded-[0.375rem] flex items-center justify-between"
            :class="[item?.value === gameType && 'bg-bg-black-4', index === 0 && 'mt-[1rem]']"
            @click="selectGameType(item?.value); dropdownVisible = false"
            >
            <span class="text-[.75rem] text-text-white-1 ml-[.5rem] font-[600]">{{ item?.label }}</span>
            <div class="size-[1rem] border-[.1875rem] border-brand rounded-[50%]"
                v-if="item?.value === gameType"></div>
            </li>
        </template>
    </BaseSheet>

    <!-- 搜索功能面板  -->
    <div
      v-show="isShowOverlay"
      @click.self="showOverlayFalse();initOthers && hideTypeSelect()"
      @touchmove.stop
    >
      <div class="scroll-y warp min-h-[80vh] mt-[1.875rem]">
        <div v-if="!resultData && !isInputing" class="no-result">
          <div class="no-result-label text-center">
            <span
              class="mb-[1.875rem] text-center"
              v-show="searchValue.length < 3"
            >{{ t('search_need_at_least_3_word') }}</span>
            <span
              v-show="searchValue.length >= 3"
            >{{ t('search_no_result') }}</span>
          </div>
          <div v-if="keywordList.length" class="mt-[1.875rem]">
            <div class="flex justify-between items-center">
              <label class="text-[0.75rem] font-[600]">{{ t('search_recent') }}</label>
              <BaseButton @click="clearKeyword" type="default" class="text-[0.75rem] font-[600]">
                {{ t('search_clear') }} ({{ keywordList.length }})
              </BaseButton>
            </div>
            <div class="flex flex-wrap gap-[0.5rem]">
              <BaseTag
                v-for="text in keywordList"
                :key="text"
                class="mb-[0.5rem]"
                :text="text"
                @click="onClickKeyword"
                @close="onCloseKeyword"
              />
            </div>
          </div>
        </div>
        <!-- casino -->
        <AppBaseSkeletonLoader :columnCount="3"  v-if="isInputing && isCasino" type="grid"/>
        <AppCardList
          v-if="isCasino && resultData && !isInputing" :list="resultData"
        />

        <!-- sports -->
         <AppBaseSkeletonLoader :columnCount="3"  v-if="isInputing && isSports" type="grid"/>
        <AppSportsSearchResult
          v-if="isSports && resultData && !isInputing" :data="sportsData"
        />
      </div>
    </div>
  </div>
</template>
